package com.yanx.system.base.domain.manager;

import cn.hutool.core.convert.Convert;
import com.yanx.common.core.domain.manager.BaseManager;
import com.yanx.common.utils.String_;
import com.yanx.system.base.domain.entity.SysDept;
import com.yanx.system.base.domain.repository.SysDeptRepository;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 部门领域服务
 *
 * @author: gotanks
 * @create: 2023-2-8
 */
@Service
public class SysDeptManager extends BaseManager<SysDept, SysDeptRepository> {

    /**
     * 检验部门名称是否唯一
     *
     * @param deptName
     * @param parentId
     * @return
     */
    public boolean checkDeptNameUnique(String deptName, Long parentId) {
        int num = repository.countByDeptNameAndParentId(deptName, parentId);
        return num > 0;
    }

    /**
     * 检验部门名称是否唯一
     *
     * @param deptName
     * @param parentId
     * @param deptId
     * @return
     */
    public boolean checkDeptNameUnique(String deptName, Long parentId, Long deptId) {
        int num = repository.countByDeptNameAndParentIdAndIdNot(deptName, parentId, deptId);
        return num > 0;
    }

    /**
     * 是否存在未停用的子部门
     *
     * @param deptId
     * @return
     */
    public boolean hasNormalChildByDeptId(Long deptId) {
        int num = repository.countNormalChildren(deptId);
        return num > 0;
    }

    /**
     * 是否存在子部门
     *
     * @param deptId
     * @return
     */
    public boolean hasChildByDeptId(Long deptId) {
        int num = repository.countChildren(deptId);
        return num > 0;
    }

    /**
     * 部门是否存在用户
     *
     * @param deptId
     * @return
     */
    public boolean checkDeptExistUser(Long deptId) {
        int num = repository.checkDeptExistUser(deptId);
        return num > 0;
    }

    /**
     * 更新子部门的祖先节点
     *
     * @param parentId
     * @param newAncestors
     */
    public void updateChildrenAncestorsByDeptId(Long parentId, String newAncestors) {
        List<SysDept> childrenDept = repository.findAllByParentId(parentId);
        childrenDept.forEach(t -> t.setAncestors(newAncestors));
        repository.saveAll(childrenDept);
    }

    /**
     * 将父部门都更新为正常
     *
     * @param ancestors
     */
    public void updateParentDeptStatusNormal(String ancestors) {
        List<Long> parentDeptIds = String_.split(ancestors, ',', -1, true, Convert::toLong);
        List<SysDept> childrenDept = repository.findAllByIdIn(parentDeptIds);
        childrenDept.forEach(t -> t.setStatus("0"));
        repository.saveAll(childrenDept);
    }
}
